<template>
  <div id="user">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!--搜索框-->
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
              v-model="searchForm.chineseName"
              placeholder="角色名称"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getRoleList">搜索</el-button>
          <el-button type="primary" @click="dialogFormVisible = true" v-if="hasAuth('trace:plot:save')">新增</el-button>
          <el-popconfirm title="确定要删除这些记录吗？" @confirm="delHandle(null)" style="margin-left: 10px;" v-if="hasAuth('sys:role:delete')">
            <el-button type="danger" slot="reference" :disabled="delBtnStu">批量删除</el-button>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!--列表-->
      <el-table
          ref="multipleTable"
          border
          stripe
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="roleName"
            label="角色字符串">
        </el-table-column>
        <el-table-column
            prop="chineseName"
            label="角色名称">
        </el-table-column>
        <el-table-column
            prop="remark"
            label="角色备注">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间">
        </el-table-column>
        <el-table-column
            width="260px"
            label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="editHandle(scope.row.roleId)" v-if="hasAuth('sys:role:update')">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" @click="editMenuHandle(scope.row.roleId)" v-if="hasAuth('sys:role:update')">分配权限</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.roleId)" v-if="hasAuth('sys:role:delete')">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--页码-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <el-dialog title="角色信息" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="editForm" :rules="editFormRules" ref="editForm">
          <el-form-item label="角色字符串" prop="roleName" label-width="100px">
            <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <el-form :model="editForm" :rules="editFormRules" ref="editForm">
          <el-form-item label="角色名称" prop="chineseName" label-width="100px">
            <el-input v-model="editForm.chineseName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <el-form :model="editForm" :rules="editFormRules" ref="editForm">
          <el-form-item label="角色备注" prop="remark" label-width="100px">
            <el-input type="textarea" autosize v-model="editForm.remark" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('editForm')">取 消</el-button>
          <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
        </div>
      </el-dialog>

      <!--分配菜单对话框-->
      <el-dialog title="分配权限" :visible.sync="roleDialogFormVisible" width="600px" @closed="resetForm('menuForm')">
        <el-form :model="menuForm" ref="menuForm">
          <el-tree
              :data="menuTreeData"
              show-checkbox
              ref="menuTree"
              node-key="menuId"
              label="name"
              :default-expand-all=true
              :props="defaultProps">
          </el-tree>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('menuForm')">取 消</el-button>
          <el-button type="primary" @click="submitSymptomForm('menuForm')">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  name: "Forest",
  data() {
    return {
      searchForm: {
        chineseName: ''
      },
      editForm: {
      },
      editFormRules: {
        roleName: [
          {required: true, message: '请输入角色字符串', trigger: 'blur'}
        ],
        chineseName: [
          {required: true, message: '请输入角色字符串', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入角色字符串', trigger: 'blur'}
        ]
      },
      current: 1,
      total: 0,
      size: 10,
      dialogFormVisible: false,
      tableData: [],
      multipleSelection: [],
      delBtnStu: true,
      roleDialogFormVisible: false,
      menuForm: {
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuTreeData:  [],
      treeCheckedKeys: [],
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    getRoleList() {
      this.$http.get('/sys/role/list', {
        params: {
          chineseName: this.searchForm.chineseName,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.data.records
        console.log(this.tableData)
        this.current = res.data.data.current
        this.size = res.data.data.size
        this.total = res.data.data.total
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getRoleList()
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post('/sys/role/' + (this.editForm.roleId? "update" : "save") ,this.editForm)
              .then(res => {
                console.log(res.data)
                this.resetForm(formName)
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getRoleList()
                  }
                });
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    submitSymptomForm(formName) {
      let menuIds = []
      menuIds = this.$refs.menuTree.getCheckedKeys()
      console.log(menuIds)
      console.log(this.menuForm)
      this.$http.post("/sys/role/perm/" + this.menuForm.roleId, menuIds).then(res => {
        this.resetForm(formName)
        this.getRoleList()
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success'
        });

      })
    },
    editHandle(id) {
      console.log(id)
      this.$http.get("/sys/role/info/" + id).then(res => {
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })
    },
    editMenuHandle(id) {
      this.$http.get('/sys/role/info/' + id).then(res => {
        const role = res.data.data
        let menuIds = []
        role.menuIds.forEach(row => {
          menuIds.push(row)
        })
        console.log("menuIds")
        console.log(res)
        this.menuForm = res.data.data
        this.$http.get("/sys/menu/list", {
          params: {
            current: 1,
            size: -1
          }
        }).then(res => {
          console.log("所有菜单")
          console.log(res)
          this.menuTreeData = res.data.data
          this.$refs.menuTree.setCheckedKeys(menuIds)
        })
        this.roleDialogFormVisible = true
      })
    },
    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.roleId)
      })
      console.log(ids)
      this.$http.post("/sys/role/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getRoleList()
          }
        });
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.dialogFormVisible = false
      this.roleDialogFormVisible = false
    }
  },
  created() {
    this.getRoleList()
  }
}
</script>
<style scoped>
#user {
  margin: 15px 10px;
}
</style>
